package
{
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLStream;
	import flash.net.URLVariables;
	
	public class CGameState_Ending extends CGameState
	{
		private var m_streamRankingData :URLStream = new URLStream();
		
		private var m_refUI :CMC_GameState_Ending = null;
		
		public function CGameState_Ending(refGame:CGame)
		{
			super(refGame);
			
			cMovieClip = new CMC_GameState_Ending();
			m_refUI = CMC_GameState_Ending(cMovieClip);
		}
		override public function EnterState() :void
		{
			m_refUI.textWholeScore.text = CGameScoreManager.instance.nScore.toString();
			m_refUI.textHighestMung.text = CGameScoreManager.instance.nHighestMungLength.toString();
			m_refUI.textName.text = "뭉뱀게임";
			
			m_refUI.btnSubmit.addEventListener(MouseEvent.MOUSE_DOWN, OnPushButton_Submit);
		}
		override public function LeaveState() :void
		{
			CGameScoreManager.instance.Clear();
			
			m_refUI.btnSubmit.removeEventListener(MouseEvent.MOUSE_DOWN, OnPushButton_Submit);
		}
		
		private function InsertRankingData(strName :String) :void
		{
			var variables :URLVariables = new URLVariables();
			variables.Raw_Score = CGameScoreManager.instance.nScore;
			variables.Raw_HighestMungLength = CGameScoreManager.instance.nHighestMungLength;
			variables.Raw_ElapsedTime = int(CGameScoreManager.instance.nElapsedTime/100);
			variables.Raw_Name = strName;

			var request :URLRequest = new URLRequest("./AZSnake_Insert_Ranking.php");
			request.method = URLRequestMethod.POST;
			request.data = variables;
			
			m_streamRankingData.addEventListener(Event.COMPLETE, OnInsertComplete);
			
			try	{ m_streamRankingData.load(request); }
			catch (error:Error) { m_refUI.textDebug.appendText("Unable to load URL: " + error); }
		}
		private function OnInsertComplete(event :Event) :void
		{
			var strRanking :String = m_streamRankingData.readMultiByte(m_streamRankingData.bytesAvailable, "euc");
			m_refUI.textDebug.appendText(strRanking);
			
			m_refGame.EnterState(CGameState.GAME_STATE_RANKING);
		}
		
		private function OnPushButton_Submit(event :MouseEvent) :void
		{
			var strName :String = m_refUI.textName.text;
			if (strName == "")
			{
				strName = "뭉뱀게임";
			}
			
			InsertRankingData(strName);
			
			CSoundManager.instance.StopSound(CSoundManager.SOUND_2_GAME);
			CSoundManager.instance.PlaySound(CSoundManager.SOUND_1_TITLE, int.MAX_VALUE);
		}
		
	}
}